package org.jeecg.modules.coupon.controller;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.models.auth.In;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.coupon.entity.MyCoupon;
import org.jeecg.modules.coupon.service.ICouponOrderService;
import org.jeecg.modules.coupon.service.IMyCouponService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.order.entity.Order;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.zixishi.entity.Quyu;
import org.jeecg.modules.zixishi.entity.Zixishi;
import org.jeecg.modules.zixishi.service.IQuyuService;
import org.jeecg.modules.zixishi.service.IZixishiService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.modules.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 我的优惠券
 * @Author: jeecg-boot
 * @Date:   2024-06-28
 * @Version: V1.0
 */
@Api(tags="我的优惠券")
@RestController
@RequestMapping("/coupon/myCoupon")
@Slf4j
public class MyCouponController extends JeecgController<MyCoupon, IMyCouponService> {
	@Autowired
	private IMyCouponService myCouponService;
	@Autowired
	private IQuyuService quyuService;
	@Autowired
	private IZixishiService zixishiService;
	@Autowired
	private ICouponOrderService couponOrderService;
	@Autowired
	private RedisUtil redisUtil;

	 /**
	 * 分页列表查询
	 *
	 * @param myCoupon
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "我的优惠券-分页列表查询")
	@ApiOperation(value="我的优惠券-分页列表查询", notes="我的优惠券-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<MyCoupon>> queryPageList(MyCoupon myCoupon,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<MyCoupon> queryWrapper = QueryGenerator.initQueryWrapper(myCoupon, req.getParameterMap());
		Page<MyCoupon> page = new Page<MyCoupon>(pageNo, pageSize);
		IPage<MyCoupon> pageList = myCouponService.page(page, queryWrapper);
		return Result.OK(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param myCoupon
	 * @return
	 */
	@AutoLog(value = "我的优惠券-添加")
	@ApiOperation(value="我的优惠券-添加", notes="我的优惠券-添加")
	//@RequiresPermissions("org.jeecg.modules:sr_my_coupon:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody MyCoupon myCoupon) {
		myCouponService.save(myCoupon);
		long days = DateUtil.betweenDay(new Date(),myCoupon.getEndDate(),true);
		redisUtil.set("mycoupon:end:" + myCoupon.getId(), "",60*60*24*days);
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param myCoupon
	 * @return
	 */
	@AutoLog(value = "我的优惠券-编辑")
	@ApiOperation(value="我的优惠券-编辑", notes="我的优惠券-编辑")
	//@RequiresPermissions("org.jeecg.modules:sr_my_coupon:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody MyCoupon myCoupon) {
		myCouponService.updateById(myCoupon);
		long days = DateUtil.betweenDay(new Date(),myCoupon.getEndDate(),true);
		redisUtil.set("mycoupon:end:" + myCoupon.getId(), "",60*60*24*days);
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "我的优惠券-通过id删除")
	@ApiOperation(value="我的优惠券-通过id删除", notes="我的优惠券-通过id删除")
	//@RequiresPermissions("org.jeecg.modules:sr_my_coupon:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		myCouponService.removeById(id);
		redisUtil.del("mycoupon:end:" + id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "我的优惠券-批量删除")
	@ApiOperation(value="我的优惠券-批量删除", notes="我的优惠券-批量删除")
	//@RequiresPermissions("org.jeecg.modules:sr_my_coupon:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.myCouponService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "我的优惠券-通过id查询")
	@ApiOperation(value="我的优惠券-通过id查询", notes="我的优惠券-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<MyCoupon> queryById(@RequestParam(name="id",required=true) String id) {
		MyCoupon myCoupon = myCouponService.getById(id);
		if(myCoupon==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(myCoupon);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param myCoupon
    */
    //@RequiresPermissions("org.jeecg.modules:sr_my_coupon:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, MyCoupon myCoupon) {
//        return super.exportXls(request, myCoupon, MyCoupon.class, "我的优惠券");
		String exportFields = this.getExportFields(MyCoupon.class,"mycoupon:");
		return super.exportXls(request, myCoupon, MyCoupon.class, "我的优惠券",exportFields);
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    //@RequiresPermissions("sr_my_coupon:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, MyCoupon.class);
    }

	 @ApiOperation(value="我的优惠券-列表查询", notes="我的优惠券-列表查询")
	 @GetMapping(value = "/myCoupon")
	 public Result<IPage<MyCoupon>> myCoupon(@RequestParam Integer useStatus, @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
											 @RequestParam(name="pageSize", defaultValue="100") Integer pageSize,
											 HttpServletRequest req) {
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 LambdaQueryWrapper<MyCoupon> queryWrapper = new LambdaQueryWrapper<MyCoupon>();
		 queryWrapper.eq(MyCoupon::getSysUserId,sysUser.getId());
		 queryWrapper.eq(MyCoupon::getUseStatus,useStatus);
		 queryWrapper.orderByDesc(MyCoupon::getUpdateTime);
		 Page<MyCoupon> page = new Page<MyCoupon>(pageNo, pageSize);
		 IPage<MyCoupon> pageList = myCouponService.page(page, queryWrapper);
		 return Result.OK(pageList);
	 }
	 @ApiOperation(value="我的优惠券详情", notes="我的优惠券详情")
	 @GetMapping(value = "/myCouponDetail")
	 public Result<MyCoupon> myCouponDetail(@RequestParam String myCouponId, HttpServletRequest req) {
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 LambdaQueryWrapper<MyCoupon> queryWrapper = new LambdaQueryWrapper<MyCoupon>();
		 queryWrapper.eq(MyCoupon::getSysUserId,sysUser.getId());
		 queryWrapper.eq(MyCoupon::getId,myCouponId);
		 MyCoupon myCoupon = myCouponService.getOne(queryWrapper);
		 if(myCoupon==null) {
			 return Result.error("没有查询到对应的卡券，请核实");
		 }
		 if(1 == myCoupon.getUseStatus() && !(myCoupon.getDurationLeft()>0)){
			 return Result.error("卡券已经使用，请核实");
		 }
		 if(myCoupon.getEffectStartDate().getTime() > new Date().getTime() || myCoupon.getEffectEndDate().getTime() < new Date().getTime()){
			 return Result.error("不在卡券使用时间范围，请核实");
		 }
		 Quyu quyu = quyuService.getById(myCoupon.getQuyuId());
		 Zixishi zixishi = zixishiService.getById(myCoupon.getZixishiId());
		 myCoupon.setQuyu(quyu);
		 myCoupon.setZixishi(zixishi);
		 return Result.OK(myCoupon);
	 }


	 @ApiOperation(value="用户卡券退款", notes="用户卡券退款")
	 @GetMapping(value = "/cancelCoupon")
	 public Result<String> cancelCoupon(@RequestParam String myCouponId) {
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 LambdaQueryWrapper<MyCoupon> queryWrapper = new LambdaQueryWrapper<MyCoupon>();
		 queryWrapper.eq(MyCoupon::getSysUserId,sysUser.getId());
		 queryWrapper.eq(MyCoupon::getId,myCouponId);
		 MyCoupon myCoupon = myCouponService.getOne(queryWrapper);
		 if(null != myCoupon && StringUtils.equals(myCoupon.getUseStatus().toString(),"0")){
			 if(StringUtils.isBlank(myCoupon.getReceiptCode())) {
				 myCoupon.setUseStatus(2);
				 myCouponService.updateById(myCoupon);
				 couponOrderService.backMoney(myCoupon.getOrderId());
				 return Result.OK();
			 }else{
				 return Result.error("不支持第三方卡券退款");
			 }
		 }else{
			 return Result.error("卡券状态不允许退款");
		 }
	 }
}
